<?php
namespace App\Api\Controllers;


use App\Http\Controllers\Controller;
use App\Models\MerchantStore;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Models\User;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class BaseController extends Controller
{

    use Helpers; //为了让所有继承这个的控制器都使用dingoApi

    public $needpage = false;//默认不要分页/

    public $l = 15;
    public $p = 1;
    public $t = 0;

    public $status = 1;
    public $message = 'ok';
    public $order_data = [];


    //交易公共进库
    public function insert_day_order($insert_data)
    {
        try {
            //如果存在base
            if (Schema::hasTable('orders_base')) {
                //后面可以不进这个数据库
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                //判断是否有表
                if (!Schema::hasTable($table)) {
                    //无表
                    DB::update('create table ' . $table . ' like 	orders_base');
                }
                $insert_data['created_at'] = date('Y-m-d H:i:s', time());
                $insert_data['updated_at'] = date('Y-m-d H:i:s', time());
                // file_put_contents('y.log',var_export($insert_data,true)."\r\n",FILE_APPEND);
                $return = DB::table($table)->insert($insert_data);
            } else {
                //订单表
                $return = Order::create($insert_data);
            }

            if (Schema::hasTable('order_items')) {
                OrderItem::create($insert_data);
            }

            return $return;
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('orders_base');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //交易公共进库
    public function insert_settle_order($insert_data)
    {
        try {
            //后面可以不进这个数据库
            $day = date('Ymd', time());
            $table = 'settle_orders_' . $day;
	    
            //判断是否有表
            if (!Schema::hasTable($table)) {
                //无表
                DB::update('create table ' . $table . ' like 	settle_order_base');
            }
	    
            $insert_data['created_at'] = date('Y-m-d H:i:s', time());
            $insert_data['updated_at'] = date('Y-m-d H:i:s', time());
            $return = DB::table($table)->insert($insert_data);
	    
            return $return;
        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('settle_orders');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


    //当天交易公共更改
    public function update_settle_order($update_data, $out_trade_no, $table = "")
    {
        try {
            if ($table == "") {
                $day = date('Ymd', time());
                $table = 'settle_orders_' . $day;
            }
	    
            $order = DB::table($table)
                ->where('out_trade_no', $out_trade_no)
                ->update($update_data);
		
            return $order;
        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('update_order');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }

    public function get_commany_name($commany_name){
        if($commany_name=='alipay'){
            $commany_name_zw='官方支付宝';
        }else if($commany_name=='weixin'){
            $commany_name_zw='官方微信';
        }else if($commany_name=='vbill'){
            $commany_name_zw='随行付';
        }else if($commany_name=='wftpay'){
            $commany_name_zw='徽商银行';
        }else if($commany_name=='hwcpay'){
            $commany_name_zw='汇旺财';
        }else if($commany_name=='nongjin'){
            $commany_name_zw='农商行';
        }else if($commany_name=='abc'){
            $commany_name_zw='农行BMP';
        }else if($commany_name=='wingpay'){
            $commany_name_zw='翼支付';
        }else if($commany_name=='pingan'){
            $commany_name_zw='平安银行';
            
        }else if($commany_name=='mybank'){
            $commany_name_zw='快钱支付';
        }else if($commany_name=='jdjr'){
            $commany_name_zw='京东聚合';
        }else if($commany_name=='newland'){
            $commany_name_zw='新大陆';
        }else if($commany_name=='vbilla'){
            $commany_name_zw='随行付A';
        }else if($commany_name=='fuiou'){
            $commany_name_zw='富友';
        }else if($commany_name=='dlb'){
            $commany_name_zw='哆啦宝';
        }else if($commany_name=='zft'){
            $commany_name_zw='花呗分期';
        }else if($commany_name=='hkrt'){
            $commany_name_zw='海科融通';
        }else if($commany_name=='easypay'){
            $commany_name_zw='易生支付';
        }else if($commany_name=='hltx'){
            $commany_name_zw='葫芦天下';
        }else if($commany_name=='lianfu'){
            $commany_name_zw='工行';
        }else if($commany_name=='lianfuyoupay'){
            $commany_name_zw='邮储银行';
        }else if($commany_name=='linkage'){
            $commany_name_zw='联动优势';
        }else if($commany_name=='weixina'){
            $commany_name_zw='微信支付a';
        }else if($commany_name=='unionpay_merch'){
            $commany_name_zw='银联商务';
        }else if($commany_name=='saobei'){
            $commany_name_zw='扫呗';
        }else if($commany_name=='abc_quiet'){
            $commany_name_zw='农行静态码';
        }else if($commany_name=='cool'){
            $commany_name_zw='酷点';
        }else if($commany_name=='gs_nongjin'){
            $commany_name_zw='甘肃农商行';
        }else if($commany_name=='ccb'){
            $commany_name_zw='建设银行';
        }else if($commany_name=='allinpay'){
            $commany_name_zw='通联支付';
        }else if($commany_name=='jiujiang'){
            $commany_name_zw='九江银行';
        }else{
            $commany_name_zw='其它';
        }
        return $commany_name_zw;
    }


    //当天交易公共更改
    public function update_day_order($update_data, $out_trade_no, $table = "")
    {
        try {

            if ($table == "") {
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
            }

            if (Schema::hasTable($table)) {
                $order = DB::table($table)
                    ->where('out_trade_no', $out_trade_no)
                    ->update($update_data);
            } 
            //else {
                $order = Order::where('out_trade_no', $out_trade_no)
                    ->update($update_data);
            //}
            //file_put_contents('bdhshdgh.log',var_export($update_data,true)."\r\n",FILE_APPEND);
            if (Schema::hasTable('order_items')) {
                OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
            }
            
            $orderdata = Order::where('out_trade_no', $out_trade_no)->first()->toarray();
            if($orderdata['company']=='wftpay' || $orderdata['company']=='nongjin' || $orderdata['company']=='pingan'|| $orderdata['company']=='saobei'|| $orderdata['company']=='ccb'|| $orderdata['company']=='jiujiang'|| $orderdata['company']=='lianfu'
            
            
             || $orderdata['company']=='cib'
            
            ){
                
                
                 //退款更改状态
                if (isset($update_data['pay_status']) && $update_data['pay_status'] == 6) {
                    error_log(date('Y-m-d H:i:s')." 【预充退款】： ".json_encode([$orderdata, $out_trade_no])."\n\n", 3, "/tmp/". 'yc-refund'.date('Ymd').".log");
                    DB::table('skill_ratastore')->where(['store_id'=>$orderdata['store_id'], 'orderNo'=>$out_trade_no])->update(['status' => 6]);
                    return true;
                }
                //退款更改状态
                
                $store=Store::where('store_id', $orderdata['store_id'])->first()->toarray();
                $rata_money = $store['rata_store'] * $orderdata['total_amount'] / 100;
                //判断该订单店铺有没有预充服务费,入是分店优先扣款分店服务费
                if($store['rata_store']>0){
                    $ratamoney=$store['store_money'];
                }
                //判断该店是否开通技术服务费扣款和该店是否是分店，如不是分店则扣款总店服务费
                if($store['rata_status']!=1 && !empty($store['pid'])){
                    $store=Store::where('id', $store['pid'])->first()->toarray();
                    if(empty($ratamoney)){
                        $ratamoney=$store['store_money'];
                        $rata_money = $store['rata_store'] * $orderdata['total_amount'] / 100;
                    }
                }
                if($store['with_user']>0){
                    $userdata= DB::table('users')->where('id', $store['with_user'])->first();
                    Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>$rata_money));
        //          服务费收取记录
                    $logs=array(
                        'store_id'=>$orderdata['store_id'],
                        'orderNo'=>$out_trade_no,
                        'order_money'=>$orderdata['total_amount'],
                        'rata_money'=>$rata_money,
                        'status'=>1,
                        'created_at'=>date("Y-m-d H:i:s",time()),
                        'updated_at'=>date("Y-m-d H:i:s",time()),
                        'user_id'=>$store['with_user']
                    );
                    DB::table('skill_ratastore')->insert($logs);
                    // $rata_store=$userdata->settlement_money-$rata_money;
                    // DB::table('users')->where('id', $userdata->id)->update(array('settlement_money'=>$rata_store));
                }else{
                    if($store['rata_status']==1 && empty($store['pid'])){
                        Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>round($rata_money,2)));
                        //服务费收取记录
                        $logs=array(
                            'store_id'=>$orderdata['store_id'],
                            'orderNo'=>$out_trade_no,
                            'order_money'=>$orderdata['total_amount'],
                            'rata_money'=>$rata_money,
                            'status'=>1,
                            'created_at'=>date("Y-m-d H:i:s",time()),
                            'updated_at'=>date("Y-m-d H:i:s",time()),
                        );
                        DB::table('skill_ratastore')->insert($logs);
                        // $rata_store=$ratamoney-round($rata_money,2);
                        // Store::where('store_id', $store['store_id'])->update(array('store_money'=>$rata_store));
                    }else if($store['rata_status']==1 && !empty($store['pid'])){
                        Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>round($rata_money,2)));
                        //服务费收取记录
                        $logs=array(
                            'store_id'=>$orderdata['store_id'],
                            'orderNo'=>$out_trade_no,
                            'order_money'=>$orderdata['total_amount'],
                            'rata_money'=>$rata_money,
                            'status'=>1,
                            'created_at'=>date("Y-m-d H:i:s",time()),
                            'updated_at'=>date("Y-m-d H:i:s",time()),
                        );
                        DB::table('skill_ratastore')->insert($logs);
                        // if($ratamoney<$rata_money){
                        //     $store=Store::where('id', $store['id'])->first()->toarray();
                        //     $ratamoney==$store['store_money'];
                        // }
                        // $rata_store=$ratamoney-round($rata_money,2);
                        // Store::where('store_id', $store['store_id'])->update(array('store_money'=>$rata_store));
                    }
                }
            }
            return $order;
        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('update_order');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


    public function parseToken($token = '')
    {
        try {
            JWTAuth::setToken(JWTAuth::getToken());
            $data = JWTAuth::getPayload();//数组
            return (object)$data['sub'];
        } catch (\Exception $e) {
            return false;
        }
    }


    public function format($cin = [])
    {
        $data = [
            'status' => $this->status,
            'message' => $this->message,
            'order_data' => $this->order_data,
            'data' => $cin
        ];
        if ($this->needpage) {

            $data['l'] = $this->l;
            $data['p'] = $this->p;
            $data['t'] = $this->t;

        }

        return response()->json($data);
    }


    /**
     *  返回分页数据
    */
    public function page($obj, $request = '')
    {

        if (empty($request))
            $request = app('request');

        $this->p = abs(trim($request->get('p', 1)));
        $this->l = abs(trim($request->get('l', 200)));

        $this->needpage = true;

        $start = abs(($this->p - 1) * $this->l);
        return $obj->offset($start)->limit($this->l);
    }


    /**
     * 校验必填字段
     */
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];
        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }
        $messages = [
            'required' => ':attribute不能为空',
        ];
        $validator = Validator::make($check, $rules,
            $messages, $attributes);
        $message = $validator->getMessageBag();
        return $message->first();
    }


    //循环获取下级的用户id
    function getSubIds($userID, $includeSelf = true, $t1 = "", $t2 = "")
    {
        $userIDs = [$userID];
        $where = [];

        if ($t2 == "") {
            $t2 = date('Y-m-d H:i:s', time());

        }

        if ($t1) {
            $where[] = ['created_at', '>=', $t1];
            $where[] = ['created_at', '<=', $t2];

        }
        while (true) {
            //不允许设置读
            $subIDs = User::whereIn('pid', $userIDs)
                ->where($where)
                ->select('id')->get()
                ->toArray();
            $subIDs = array_column($subIDs, 'id');
            $userCount = count($userIDs);
            $userIDs = array_unique(array_merge($userIDs, $subIDs));
            if ($userCount == count($userIDs)) {
                break;
            }
        }
        if (!$includeSelf) {
            for ($i = 0; $i < count($userIDs); ++$i) {
                if ($userIDs[$i] == $userID) {
                    array_splice($userIDs, $i, 1);
                    break;
                }
            }
        }
        return $userIDs;
    }
    

    /**
     * 查询门店所有ID
     * @return string
     */
    public function getStore_id($store_id, $id)
    {

        $store_ids = [];

        $store = Store::orWhere('pid', $id)
            ->orWhere('store_id', $store_id)
            ->select('store_id')
            ->get();

        if (!$store->isEmpty()) {
            $store_ids = $store->toArray();
        }

        return $store_ids;

    }

    /**
     * 操作日志
     * 2022-07-19 15:56
     */
    function operation_log($agent_id, $type, $remark, $pass_id = 0){
//        print_r($remark);die;
        if( isset($agent_id) && isset($remark) ){
            $data = [
                'agent_id' => $agent_id,
                'pass_id' => $pass_id,
                'remark' => $remark,
                'ip' => $_SERVER["REMOTE_ADDR"],
                'type' => $type,
                'create_time' => date('Y-m-d H:i:s'),
            ];
//            print_r($data);die;
            DB::table('operation_log')->where(['1'=>1])->insert($data);
        }
    }
    
    public function get_commission($agent_id, $date)
    {
        $amount = 0;
        $explode = explode(',', $date);
        $agent_rate = [];
        $sales_ids = [$agent_id];
        $agent_level = DB::table('users')->where('id', $agent_id)->value('level');
        if ($agent_id != 1) {
            if ($agent_level == 2) {
                $sales_ids = DB::table('users')->where('id', $agent_id)->orWhere('pid', $agent_id)->pluck('id');
            }
        }
        $pluck = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
            ->whereIn('receive_model', [2, 3, 4])
            ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                if ($agent_level == 1) {
                    $query->where('agent_id', $agent_id);
                }
                if (in_array($agent_level, [2, 3])) {
                    $query->whereIn('sales_id', $sales_ids);
                }
                return $query;
            })
            ->where('receive_rate', '>', 0)
            ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
            ->groupBy('receive_code');
        if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
            $union_pluck =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->groupBy('receive_code');
            $pluck->unionAll($union_pluck);
        }
        $pluckArray = $pluck->pluck('receive_model','receive_code')->toArray();
        $ratesObj = DB::table('user_rates')
            ->where('user_id', $agent_id)
            ->whereIn('ways_type', array_keys($pluckArray))
            ->select(['id', 'ways_type', 'rate', 'rate_a', 'rate_e', 'server_rate', 'yu_rate', 'era_rate'])->get();
        foreach ($ratesObj as $obj) {
            //8005, 6005  rate_e   如果是刷卡费率读取
            if (in_array($obj->ways_type, [8005, 6005])) {
                $obj->rate = $obj->rate_e;
            }
            //8004, 6004  rate_a   如果是银联扫码费率读取
            if (in_array($obj->ways_type, [8004, 6004])) {
                $obj->rate = $obj->rate_a;
            }
            switch ($pluckArray[$obj->ways_type]){
                case 1://服务费模式
                    $obj->rate = $obj->server_rate;
                    break;
                case 2://代扣模式
                    $obj->rate = $obj->era_rate;
                    break;
                case 3://通道
                    $obj->rate = $obj->rate;
                    break;
                case 4://预充
                    $obj->rate = $obj->yu_rate;
                    break;
            }
            
            $agent_rate[$obj->ways_type] = (array)$obj;
            $query = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
                ->where('receive_code', $obj->ways_type)
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->select([
                    DB::raw("sum(order_amount-refund_amount) as order_amount"),
                    DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                    // DB::raw("sum(round((order_amount-refund_amount) * (receive_rate/100))) as receive_fee"),
                    DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                ]);
            if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
                $union =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                    ->where('receive_code', $obj->ways_type)
                    ->whereIn('receive_model', [2, 3, 4])
                    ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                        if ($agent_level == 1) {
                            $query->where('agent_id', $agent_id);
                        }
                        if (in_array($agent_level, [2, 3])) {
                            $query->whereIn('sales_id', $sales_ids);
                        }
                        return $query;
                    })
                    ->where('receive_rate', '>', 0)
                    ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                    ->select([
                        DB::raw("sum(order_amount-refund_amount) as order_amount"),
                        DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                        // DB::raw("sum(round((order_amount-refund_amount) * (receive_rate/100))) as receive_fee"),
                        DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                    ]);
                $query = $query->unionAll($union);
            }
            foreach ($query->get() as $obj) {
                $amount += ($obj->receive_fee - $obj->agent_fee);
            }
        }
        return bcdiv($amount, 100, 2);
    }
    
    public function get_commission_company($agent_id, $date,$pluckArray)
    {
        $amount = 0;
        $explode = explode(',', $date);
        $agent_rate = [];
        $sales_ids = [$agent_id];
        $agent_level = DB::table('users')->where('id', $agent_id)->value('level');
        if ($agent_id != 1) {
            if ($agent_level == 2) {
                $sales_ids = DB::table('users')->where('id', $agent_id)->orWhere('pid', $agent_id)->pluck('id');
            }
        }
        $pluckArray = $pluckArray;
        $ratesObj = DB::table('user_rates')
            ->where('user_id', $agent_id)
            ->whereIn('ways_type', $pluckArray)
            ->select(['id', 'ways_type', 'rate', 'rate_a', 'rate_e', 'server_rate', 'yu_rate', 'era_rate'])->get();
        foreach ($ratesObj as $obj) {
            //8005, 6005  rate_e   如果是刷卡费率读取
            if (in_array($obj->ways_type, [8005, 6005])) {
                $obj->rate = $obj->rate_e;
            }
            //8004, 6004  rate_a   如果是银联扫码费率读取
            if (in_array($obj->ways_type, [8004, 6004])) {
                $obj->rate = $obj->rate_a;
            }
            $agent_rate[$obj->ways_type] = (array)$obj;
            $query = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
                ->where('receive_code', $obj->ways_type)
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->select([
                    DB::raw("sum(order_amount-refund_amount) as order_amount"),
                    DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                    DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                ]);
            if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
                $union =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                    ->where('receive_code', $obj->ways_type)
                    ->whereIn('receive_model', [2, 3, 4])
                    ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                        if ($agent_level == 1) {
                            $query->where('agent_id', $agent_id);
                        }
                        if (in_array($agent_level, [2, 3])) {
                            $query->whereIn('sales_id', $sales_ids);
                        }
                        return $query;
                    })
                    ->where('receive_rate', '>', 0)
                    ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                    ->select([
                        DB::raw("sum(order_amount-refund_amount) as order_amount"),
                        DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                        DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                    ]);
                $query = $query->unionAll($union);
            }
            foreach ($query->get() as $obj) {
                $amount += ($obj->receive_fee - $obj->agent_fee);
            }
        }
        return bcdiv($amount, 100, 2);
    }
    
    public function get_commission_company_store($agent_id, $date,$pluckArray1,$store_id)
    {
        $amount = 0;
        $explode = explode(',', $date);
        $agent_rate = [];
        $sales_ids = [$agent_id];
        $agent_level = DB::table('users')->where('id', $agent_id)->value('level');
        if ($agent_id != 1) {
            if ($agent_level == 2) {
                $sales_ids = DB::table('users')->where('id', $agent_id)->orWhere('pid', $agent_id)->pluck('id');
            }
        }
        $pluck = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
            ->whereIn('receive_model', [2, 3, 4])
            ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$pluckArray1) {
                if ($agent_level == 1) {
                    $query->where('agent_id', $agent_id);
                }
                if (in_array($agent_level, [2, 3])) {
                    $query->whereIn('sales_id', $sales_ids);
                }
                $query->whereIn('receive_code', $pluckArray1);
                return $query;
            })
            ->where('receive_rate', '>', 0)
            ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
            ->groupBy('receive_code');
        if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
            $union_pluck =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$pluckArray1) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    $query->whereIn('receive_code', $pluckArray1);
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->groupBy('receive_code');
            $pluck->unionAll($union_pluck);
        }
        $pluckArray = $pluck->pluck('receive_model','receive_code')->toArray();
        $ratesObj = DB::table('user_rates')
            ->where('user_id', $agent_id)
            ->whereIn('ways_type', array_keys($pluckArray))
            ->select(['id', 'ways_type', 'rate', 'rate_a', 'rate_e', 'server_rate', 'yu_rate', 'era_rate'])->get();
        foreach ($ratesObj as $obj) {
            //8005, 6005  rate_e   如果是刷卡费率读取
            if (in_array($obj->ways_type, [8005, 6005])) {
                $obj->rate = $obj->rate_e;
            }
            //8004, 6004  rate_a   如果是银联扫码费率读取
            if (in_array($obj->ways_type, [8004, 6004])) {
                $obj->rate = $obj->rate_a;
            }
            switch ($pluckArray[$obj->ways_type]){
                case 1://服务费模式
                    $obj->rate = $obj->server_rate;
                    break;
                case 2://代扣模式
                    $obj->rate = $obj->era_rate;
                    break;
                case 3://通道
                    $obj->rate = $obj->rate;
                    break;
                case 4://预充
                    $obj->rate = $obj->yu_rate;
                    break;
            }
            $agent_rate[$obj->ways_type] = (array)$obj;
            $query = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
                ->where('receive_code', $obj->ways_type)
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$store_id) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    $query->where('store_id', $store_id);
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->select([
                    DB::raw("sum(order_amount-refund_amount) as order_amount"),
                    DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                    DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                ]);
            if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
                $union =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                    ->where('receive_code', $obj->ways_type)
                    ->whereIn('receive_model', [2, 3, 4])
                    ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$store_id) {
                        if ($agent_level == 1) {
                            $query->where('agent_id', $agent_id);
                        }
                        if (in_array($agent_level, [2, 3])) {
                            $query->whereIn('sales_id', $sales_ids);
                        }
                        $query->where('store_id', $store_id);
                        return $query;
                    })
                    ->where('receive_rate', '>', 0)
                    ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                    ->select([
                        DB::raw("sum(order_amount-refund_amount) as order_amount"),
                        DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                        DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                    ]);
                $query = $query->unionAll($union);
            }
            foreach ($query->get() as $obj) {
                $amount += ($obj->receive_fee - $obj->agent_fee);
            }
        }
        return bcdiv($amount, 100, 2);
    }
    
    public function get_commission_store($agent_id, $date,$store_id)
    {
        $amount = 0;
        $explode = explode(',', $date);
        $agent_rate = [];
        $sales_ids = [$agent_id];
        $agent_level = DB::table('users')->where('id', $agent_id)->value('level');
        if ($agent_id != 1) {
            if ($agent_level == 2) {
                $sales_ids = DB::table('users')->where('id', $agent_id)->orWhere('pid', $agent_id)->pluck('id');
            }
        }
        $pluck = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
            ->whereIn('receive_model', [2, 3, 4])
            ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                if ($agent_level == 1) {
                    $query->where('agent_id', $agent_id);
                }
                if (in_array($agent_level, [2, 3])) {
                    $query->whereIn('sales_id', $sales_ids);
                }
                return $query;
            })
            ->where('receive_rate', '>', 0)
            ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
            ->groupBy('receive_code');
        if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
            $union_pluck =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->groupBy('receive_code');
            $pluck->unionAll($union_pluck);
        }
        $pluckArray = $pluck->pluck('receive_model','receive_code')->toArray();
        $ratesObj = DB::table('user_rates')
            ->where('user_id', $agent_id)
            ->whereIn('ways_type', array_keys($pluckArray))
            ->select(['id', 'ways_type', 'rate', 'rate_a', 'rate_e', 'server_rate', 'yu_rate', 'era_rate'])->get();
        foreach ($ratesObj as $obj) {
            //8005, 6005  rate_e   如果是刷卡费率读取
            if (in_array($obj->ways_type, [8005, 6005])) {
                $obj->rate = $obj->rate_e;
            }
            //8004, 6004  rate_a   如果是银联扫码费率读取
            if (in_array($obj->ways_type, [8004, 6004])) {
                $obj->rate = $obj->rate_a;
            }
            switch ($pluckArray[$obj->ways_type]){
                case 1://服务费模式
                    $obj->rate = $obj->server_rate;
                    break;
                case 2://代扣模式
                    $obj->rate = $obj->era_rate;
                    break;
                case 3://通道
                    $obj->rate = $obj->rate;
                    break;
                case 4://预充
                    $obj->rate = $obj->yu_rate;
                    break;
            }
            $agent_rate[$obj->ways_type] = (array)$obj;
            $query = DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[0])) . '_bill')
                ->where('receive_code', $obj->ways_type)
                ->whereIn('receive_model', [2, 3, 4])
                ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$store_id) {
                    if ($agent_level == 1) {
                        $query->where('agent_id', $agent_id);
                    }
                    if (in_array($agent_level, [2, 3])) {
                        $query->whereIn('sales_id', $sales_ids);
                    }
                    $query->where('store_id', $store_id);
                    return $query;
                })
                ->where('receive_rate', '>', 0)
                ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                ->select([
                    DB::raw("sum(order_amount-refund_amount) as order_amount"),
                    DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                    DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                ]);
            if (date('Ym', strtotime($explode[1])) - date('Ym', strtotime($explode[0])) > 0) {
                $union =  DB::connection('old_mysql')->table('wft_stores_orders_' . date('Ym', strtotime($explode[1])) . '_bill')
                    ->where('receive_code', $obj->ways_type)
                    ->whereIn('receive_model', [2, 3, 4])
                    ->where(function ($query) use (&$agent_id, &$sales_ids, &$agent_level, &$store_id) {
                        if ($agent_level == 1) {
                            $query->where('agent_id', $agent_id);
                        }
                        if (in_array($agent_level, [2, 3])) {
                            $query->whereIn('sales_id', $sales_ids);
                        }
                        $query->where('store_id', $store_id);
                        return $query;
                    })
                    ->where('receive_rate', '>', 0)
                    ->whereBetween('bill_date', [strtotime($explode[0] . ' 00:00:00'), strtotime($explode[1] . ' 23:59:59')])
                    ->select([
                        DB::raw("sum(order_amount-refund_amount) as order_amount"),
                        DB::raw("sum(receive_fee-receive_refund_fee) as receive_fee"),
                        DB::raw("sum(round((order_amount-refund_amount) * ($obj->rate/100))) as agent_fee")
                    ]);
                $query = $query->unionAll($union);
            }
            foreach ($query->get() as $obj) {
                $amount += ($obj->receive_fee - $obj->agent_fee);
            }
        }
        return bcdiv($amount, 100, 2);
    }
    
    /**
     * 验证密钥
     * 2022/09/29 11:57
     */
    function pass_verify($pass, $pash){
        $pass = $pass;
        if(!$pass){
            return json_encode([
                'status' => 2,
                'message' => '请输入密钥'
            ]);
        }
        $permission = DB::table('pass')->where(['pass_md5' => md5($pass)])->first(); // 查询密钥
        if(!$permission){
            return json_encode([
                'status' => 2,
                'message' => '密钥不存在'
            ]);
        }

        $path = $pash; // 请求api地址
        $permission = DB::table('pass_permission')->where(['pass_id' => $permission->id, 'permission_api' => $path])->first(); // 验证密钥权限
        if(!$permission){
            return json_encode([
                'status' => 2,
                'message' => '密钥不正确或无权限'
            ]);
        }

        return json_encode([
            'status' => 1,
            'message' => '验证通过'
        ]);
    }
}
